<template>
	<view>
		<input class="uni-input" @input="onKeyInput" placeholder="输入同步到view中" />

		<view>
			<button @click="qk">清空</button>
			历史记录:
			<view v-if="searchList.length" class='searchjl'>
				<view v-for="(item,index) in searchList" :key='index'>
					{{item}}
				</view>
			</view>
			<view v-else>还没有搜索记录</view>
		</view>
		<view v-for="(item,index) in list" :key='index'>
			<view>
				<image :src='item.img' />
			</view>
			<view>{{item.title}}</view>
			<view>{{item.id}}</view>
		</view>
	</view>
</template>

<script setup>
	import {
		onLoad,
	} from '@dcloudio/uni-app'
	import {
		ref
	} from 'vue'
	import {
		debounce,
	} from 'lodash'
	let list = ref([])
	let inputValue = ref("")
	let searchList = ref(uni.getStorageSync("searchList")) || ref([])

	const qk = () => {
		searchList.value = []
		uni.setStorageSync("searchList", searchList.value)
	}

	const onKeyInput = debounce((event) => {
		if (event.target.value !== '') {
			uni.request({
				url: "http://localhost:3000/search",
				data: {
					items: event.target.value
				}
			}).then((resp) => {
				let {
					items
				} = resp.data
				list.value = items
			})
			if (searchList.value.indexOf(event.target.value) == -1) {
				searchList.value.unshift(event.target.value)
				uni.setStorageSync("searchList", searchList.value)
			} else {
				searchList.value.splice(searchList.value.indexOf(event.target.value), 1)
				searchList.value.unshift(event.target.value)
				uni.setStorageSync("searchList", searchList.value)
			}
		} else {
			uni.request({
				url: "http://localhost:3000/search",
				data: {
					items: ""
				}
			}).then((resp) => {
				let {
					items
				} = resp.data
				list.value = items
			})
		}
	}, 500)
	const getList = () => {
		uni.request({
			url: "http://localhost:3000/list"
		}).then((resp) => {
			list.value = resp.data.list
		})
	}
	onLoad(() => {
		getList()
	})
</script>

<style lang="scss">
	.searchjl {
		display: flex;
	}

	.searchjl view {
		background: #ccc;
		color: red;
		margin-right: 5px;
	}

	image {
		width: 100px;
		height: 100px;
	}
</style>